import React, { Component } from 'react';
import $ from 'jquery';
import './scss/CreateNotice.scss';
import { getData, getQueryVariable } from '../../common/js/fetch';
import {
    LgInput, LgTextarea, LgRadio, LgCheckbox, LgButton, LgCascader, LgEmpty,
    LgSwitch, LgSelect, LgPopLayer, LgUpload, LgLoadingDotRotation, LgPageFooter, LgDatePicker
} from 'lancoo-web-ui';
import Scrollbars from "react-custom-scrollbars";
import { message, Spin } from "antd";
import CollectSelectModal from "./common/collectSelectModal";
import MyEditor from './MyEditor';
import Base64 from '../../common/js/fetch/base64'
import SelectUserModal from "lg-select-modal";
import { SKIN_BG_COLOR } from '../../hooks/useGetThem'

const groupTypeInfo = {
    "admin": "管理员",
    "tea": "教师",
    "stu": "学生",
    "parent": "家长",
    "myClass": "学生",
    "classParent": "家长",
    "myGroup": "教师",
    "org": "部门"
}


let typeArr = ['doc', 'docx', 'pdf', 'jpg', 'jpeg', 'png', 'xls', 'zip', 'ppt'];
function GetExtensionFileName(pathfilename) {
    var reg = /(\\+)/g;
    var pfn = pathfilename.replace(reg, "#");
    var arrpfn = pfn.split("#");
    var fn = arrpfn[arrpfn.length - 1];
    var arrfn = fn.split(".");
    return arrfn[arrfn.length - 1];
}


class CreateNotice extends Component {
    constructor(props) {

        super(props);
        this.state = {
            userInfo: JSON.parse(sessionStorage.getItem('userInfo')),
            schoolInfo: JSON.parse(sessionStorage.getItem('schoolSystemInfo')),
            datalistA: [
                {
                    text: "全部状态",
                },
                {
                    text: "已发布",
                },
                {
                    text: "未发布",
                },
            ],
            selectValue: "全部状态",
            group: [
                // { label: '管理员', value: 6, checked: false },
                // { label: '领导', value: 8, checked: false },
                // { label: '学生', value: 2, checked: false },
                // { label: '家长', value: 3, checked: false },
                // { label: '其他', value: 11, checked: false },
            ],
            radioValue: 0,
            toped: false,
            synced: false,
            releaseDepList: [],
            selectDepList: [],
            selectUserVisible: false,
            selectUserList: [],
            receiverType: "",
            receiverInfo: {},
            totalNum: 0,
            isShowSelectObj: false,
            classList: [],
            buildList: [],
            boardList: [],
            chooseDeviceList: [],
            selectDeviceList: [],
            isShowBuildList: false,
            isShowClassList: false,
            isShowBoardList: false,
            isShowSelectDep: false,
            loading: false,
            attachments: [],
            isFirstTime: true, // 设置标志位
            searchDeviceList: [],
            allDeviceList: [],
            forceHidden: true,
            over: false,//以下均为新增
            oldEditId: '',
            noticeTitle: '',
            noticeContent: '',
            officePlatform: JSON.parse(sessionStorage.getItem('officePlatform')) || this.props.officePlatform,
            cascaderValue: undefined,
            group1: [],//2023-07-05只让修改初始就被选中的对象
            isAdvancedAdmin: sessionStorage.getItem('isAdvanced'),
            titleWarn: false,
            contentWarn: false,
            innerTypeId: null,
            date: new Date(),
        }
    }
    componentDidMount() {
        console.log(this.props, '666666666666')
        console.log(this.props.typeId)
        if (this.props.editId !== '') {
            this.setState({
                over: true,
            }, () => {
                console.log(this.state.over)
                this.editDetail(this.props.editId);
            });
        }

        if (!this.props.isAdvanced) {
            $('.advanced-settings-bottom').hide();
        } else {
            $('.advanced-settings-bottom').show();
        }
        if (this.props.typeList.length > 0 && this.state.isFirstTime) {
            let obj = this.props.typeList[0];
            console.log(this.props.typeList)
            console.log(obj)
            console.log(this.state.group)
            // let group = this.state.group, group1 = [];
            let group = []
            let group1 = [];
            if (obj.scopeIdentityList.length > 0) {
                obj.scopeIdentityList.forEach(i => {
                    group.push({
                        label: i.identityName, value: i.identityCode, checked: false
                    })
                })
                group.forEach(item => {
                    item.checked = false;
                    obj.scope.forEach(itm => {
                        if (item.value == itm) {
                            item.checked = true;
                            group1.push(item)
                        }
                    })
                })
            }
            console.log('group', group1);

            this.setState({
                group,
                group1,
                isFirstTime: false// 将标志位置为 false
            }, () => {
                this.props.setReleaseScope(group);
            })
        }
    }


    componentWillReceiveProps(nextProps) {
        if (!nextProps.isAdvanced) {
            $('.advanced-settings-bottom').hide();
        } else {
            $('.advanced-settings-bottom').show();
        }
    }

    //查看已撤回的公告详情
    editDetail = (bulletinId) => {
        getData("api/bulletin/info/edit/detail", {
            bulletinId
        })
            .then((res) => {
                return res.json()
            })
            .then((result) => {
                console.log(result)
                if (result.code == 200) {
                    let data = result.data;
                    //恢复类型
                    let selectTypeIndex = 0;
                    console.log(this.props.typeList)
                    this.props.typeList.forEach((item, index) => {
                        if (item.typeId === data.typeId) {
                            this.checkItem((item.typeId), item);
                            selectTypeIndex = index;
                        }
                    })
                    //需要将选择对象还原成可识别的数组
                    let receiveInfo = data.receiver ? data.receiver : {};

                    let list = [], deviceList = [], fileList = [];
                    for (let key in receiveInfo) {
                        // if (!Array.isArray(receiveInfo[key])) {
                        //     return;
                        // }
                        if (key === "persons" && receiveInfo[key] != null) {
                            receiveInfo[key].forEach((item) => {
                                list.push({
                                    ...item,
                                    id: item.userId,
                                    name: item.userName,
                                    type: "user",
                                    floorNum: 6,
                                    groupType: item.userType == 6 ? "admin" : 'leader'
                                })
                            })
                        }
                        if (key === "leaders" && receiveInfo[key] != null) {
                            receiveInfo[key].forEach((item) => {
                                list.push({
                                    ...item,
                                    type: "leader",
                                    groupType: "leader"
                                })
                            })
                        }
                        // if (key === "classes") {
                        //     receiveInfo[key].forEach((item) => {
                        //         list.push({
                        //             ...item,
                        //             id: item.classId,
                        //             name: item.className
                        //         })
                        //     })
                        // }
                        // if (key === "students") {
                        //     receiveInfo[key].forEach((item) => {
                        //         list.push({
                        //             ...item,
                        //             id: item.classId || item.gradeId || item.majorId || item.collegeId,
                        //             name: item.className || item.gradeName || item.majorName || item.collegeName,
                        //             floorNum: item.classId ? 5 : item.gradeId ? 4 : item.majorId ? 3 : 2,
                        //             type: item.classId ? "class" : item.gradeId ? "grade" : item.majorId ? "major" : "college",
                        //             groupType: "stu"
                        //         })
                        //     })
                        // }
                        // if (key === "parents") {
                        //     receiveInfo[key].forEach((item) => {
                        //         list.push({
                        //             ...item,
                        //             id: item.classId || item.gradeId || item.majorId || item.collegeId,
                        //             name: item.className || item.gradeName || item.majorName || item.collegeName,
                        //             floorNum: item.classId ? 5 : item.gradeId ? 4 : item.majorId ? 3 : 2,
                        //             type: item.classId ? "class" : item.gradeId ? "grade" : item.majorId ? "major" : "college",
                        //             groupType: "parent"
                        //         })
                        //     })
                        // }
                        // if (key === "teachers") {
                        //     receiveInfo[key].forEach((item) => {
                        //         list.push({
                        //             ...item,
                        //             id: item.subjectId || item.groupId || item.collegeId,
                        //             name: item.subjectName || item.groupName || item.collegeName,
                        //             floorNum: item.subjectId || item.groupId ? 3 : 2,
                        //             type: item.subjectId || item.groupId ? "group" : "college",
                        //             groupType: "tea"
                        //         })
                        //     })
                        // }
                        if (key === "identities" && receiveInfo[key] != null) {
                            receiveInfo[key].forEach((item) => {
                                list.push({
                                    ...item,
                                    id: item.identityCode,
                                    name: item.identityName,
                                    floorNum: 2,
                                    type: "identity",
                                    groupType: "admin"
                                })
                            })
                        }
                        if (key === "departments" && receiveInfo[key] != null) {
                            receiveInfo[key].forEach((item) => {
                                list.push({
                                    ...item,
                                    id: item.departmentId,
                                    name: item.departmentName,
                                    type: "org",
                                    groupType: "org"
                                })
                            })
                        }
                        if (key === "devices" && receiveInfo[key] != null) {  //如何转过来的就要转回去才能识别
                            receiveInfo[key].forEach((item) => {
                                if (item.deviceType == 1) {  //班牌
                                    deviceList.push({
                                        boardId: item.deviceId,
                                        boardName: item.deviceName,
                                    })
                                } else if (item.deviceType == 2) {  //楼牌
                                    deviceList.push({
                                        buildingBoardId: item.deviceId,
                                        buildingBoardName: item.deviceName
                                    })
                                } else {
                                    deviceList.push({
                                        buildingId: item.deviceId,
                                        buildingName: item.deviceName
                                    })
                                }
                            })
                        }
                    }
                    //恢复附件
                    if (data.attachments) {
                        fileList = data.attachments.map((item) => {
                            return {
                                ...item,
                                fileName: item.name
                            }
                        })
                    }

                    this.setState({
                        over: false,
                        noticeTitle: data.title,
                        selectDepList: [
                            {
                                departmentName: data.departmentName,
                                departmentId: data.departmentId,
                            }
                        ],
                        cascaderValue: data.departmentName,
                        receiverInfo: receiveInfo,
                        selectUserList: list,
                        selectDeviceList: deviceList,
                        noticeContent: data.content,
                        toped: data.seat === '1' ? true : false,
                        synced: data.pushOfficialWebsite === '1' ? true : false,
                        attachments: fileList,
                        radioValue: selectTypeIndex,
                        innerTypeId,
                        date: data?.displayEndTime
                            ? dayjs(data.displayEndTime, 'YYYY-MM-DD HH:mm:ss').toDate()
                            : new Date()
                    }, () => {
                        this.props.setIsTop(this.state.toped === true ? '1' : '0');
                        this.props.setAttachmentsList(this.state.attachments);
                        this.props.setDevices(this.state.selectDeviceList);
                        this.props.setIsSynced(this.state.synced === true ? '1' : '0');
                        this.props.setNoticeContent(this.state.noticeContent);
                        this.props.setNoticeTitle(this.state.noticeTitle);
                        this.props.setReceiver(this.state.receiverInfo);
                        this.props.setReleaseDepartment(this.state.selectDepList);
                        this.props.setDisplayEndTime(this.state.date || null);
                        this.setState({ over: false });
                        if (data.seat === '1' || data.pushOfficialWebsite === '1' || data.receiver.length > 0) {
                            this.props.setAdvanced(true)
                        }
                    })

                }
            })
    }

    //初始化
    init = () => {
        this.setState({
            noticeTitle: '',
            selectDepList: [],
            receiverInfo: {},
            selectUserList: [],
            selectDeviceList: [],
            noticeContent: '',
            toped: false,
            synced: false,
            attachments: [],
            radioValue: 0,
        }, () => {
            this.props.setIsTop(this.state.toped === true ? '1' : '0');
            this.props.setAttachmentsList(this.state.attachments);
            this.props.setDevices(this.state.selectDeviceList);
            this.props.setIsSynced(this.state.synced === true ? '1' : '0');
            this.props.setNoticeContent(this.state.noticeContent);
            this.props.setNoticeTitle(this.state.noticeTitle);
            this.props.setReceiver(this.state.receiverInfo);
            this.props.setReleaseDepartment(this.state.selectDepList);
            this.props.setDisplayEndTime(this.state.date || null);
            this.props.setAdvanced(false)
        })
    }

    onChange = (checked, index) => {
        console.log(this.props.typeList)
        console.log(checked)
        console.log(index)
        let canViewList = this.state.group1.concat([]);//2023-07-05将group修改为group1
        const newData = [...canViewList]
        canViewList[index].checked = checked
        this.setState({
            group1: newData
        }, () => {
            this.props.setReleaseScope(newData);
        })
    }
    SelectOptionA = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValue: item.text
        }, () => {

        })
    }

    selectUserChange1 = (value) => {
        this.setState({
            selectUserVisible: value
        })
    }

    //获取发布部门
    getReleaseDep = (type) => {
        if (type === 1) {
            this.setState({ isShowSelectDep: true })
            getData("api/commons/school/department/list", {
                sysId: this.state.schoolInfo.noticeSysId,
                schoolId: this.state.schoolInfo.schoolId,
                departmentId: ''
            })
                .then((res) => {
                    return res.json()
                })
                .then((result) => {
                    if (result.code == 200 && Array.isArray(result.data)) {
                        let data = result.data;
                        this.setState({
                            releaseDepList: data
                        })
                    }
                })
        }
    }
    chooseDep = (obj) => {
        console.log('objobjobj', obj);
        let { selectDepList } = this.state
        let newList = [];
        let sign = 0;
        selectDepList.forEach((item) => {
            if (item.departmentId === obj.departmentId) { //已存在
                sign = 1;
            }
        })
        if (sign === 0) {
            if (selectDepList.length > 0) {
                message.warn('发布部门只能选择一个！');
                return;
            }
            selectDepList.push(obj);
            newList = selectDepList;
            this.props.setReleaseDepartment(newList);
        } else {
            selectDepList.forEach((item) => {
                if (item.departmentId !== obj.departmentId) {
                    newList.push(item);
                    this.props.setReleaseDepartment(newList);
                }
            })

        }
        this.setState({
            selectDepList: newList
        })
    }
    deleteDep = (index) => {
        let {
            selectDepList
        } = this.state;
        selectDepList.splice(index, 1);
        this.setState({
            selectDepList: selectDepList
        })
    }

    //获取选择的用户列表
    getSelectList1 = (obj) => {
        let receiveType = this.state.receiverType;
        let receiverType2 = [];
        const keyInfo = {
            "stu": "学生",
            "parent": "家长",
            "tea": "老师",
            "admin": "管理员",
            "org": "部门",
            "person": "个人"
        }
        if (Array.isArray(obj.groupList)) {
            obj.groupList.forEach((item) => {
                if (item.check == 2) {
                    if (item.exact) {
                        if (receiverType2.indexOf("全部" + keyInfo[item.id]) !== -1) {
                            return;
                        }
                        receiverType2.push("部分" + keyInfo[item.id]);
                        return;
                    }
                    if (receiverType2.indexOf("部分" + keyInfo[item.id]) !== -1) {
                        receiverType2.splice(receiverType2.indexOf("部分" + keyInfo[item.id]), 1);
                    }
                    receiverType2.push("全部" + keyInfo[item.id]);
                }
                if (item.check == 1) {
                    if (receiverType2.indexOf("全部" + keyInfo[item.id]) !== -1) {
                        return;
                    }
                    receiverType2.push("部分" + keyInfo[item.id]);
                }
            })
        }
        if (obj.persons && obj.persons.length > 0) {
            receiverType2.push("个人");
            obj.persons.forEach((item) => {
                if (!item.photoPath) {
                    item.photoPath = item.PhotoPath;
                }
            })
        }

        receiverType2 = [...new Set(receiverType2)].join("、");
        let updateStr = [];
        receiveType.split("、").forEach((item) => {
            if (
                item.indexOf("学生") === -1 &&
                item.indexOf("家长") === -1 &&
                item.indexOf("老师") === -1 &&
                item.indexOf("管理员") === -1 &&
                item.indexOf("部门") === -1 &&
                item.indexOf("个人") === -1) {
                updateStr.push(item);
            }
        })
        console.log('obj', obj);

        updateStr = updateStr.join("、");
        console.log(receiverType2 + (updateStr ? "、" : "") + updateStr, 'receiverType', obj, 'receiverInfo');
        this.setState({
            receiverType: receiverType2 + (updateStr ? "、" : "") + updateStr,
            receiverInfo: obj,
            selectUserList: Array.isArray(obj.allList) ? obj.allList : []
        }, () => this.props.setReceiver(obj))
    }
    deleteSelectedUser = (index) => {
        let {
            selectUserList
        } = this.state;
        let total = 0;
        selectUserList.splice(index, 1);
        selectUserList.forEach(item => {
            total += Number(item.totalCount);
            return total
        })
        this.setState({
            selectUserList,
            totalNum: total
        })
    }
    clear = (type) => {
        if (type === 1) {
            this.setState({
                selectUserList: [],
                totalNum: 0
            })
        }
    }

    showSelectDevice = (type) => {
        //type : 1是选择， 0是重选
        //获取班牌、楼牌、广播终端
        if (type === 0) {
            //重选时需要把之前存储的已选设备清空
            this.setState({
                chooseDeviceList: [],
                selectDeviceList: []
            })
            return;
        }
        let userId = this.state.userInfo.userId;
        getData("api/commons/device/class/boards")
            .then((res) => {
                return res.json()
            })
            .then((result) => {
                if (result.code == 200 && Array.isArray(result.data)) {
                    let arr = this.state.allDeviceList.concat(result.data);
                    this.setState({
                        classList: result.data,
                        allDeviceList: arr,
                    })
                }
            })
        getData("api/commons/device/building/boards")
            .then((res) => {
                return res.json()
            })
            .then((result) => {
                if (result.code == 200 && Array.isArray(result.data)) {
                    let updateList = [];
                    result.data.forEach((item) => {
                        updateList.push({
                            // buildingBoardId: item.buildingBoardType,
                            // buildingBoardName: buildingBoardTypeInfo[item.buildingBoardType]
                            // 处理楼牌同名只显示  名为  楼牌  的多个楼牌2023-07-21
                            buildingBoardId: item.buildingBoardId,
                            buildingBoardName: item.buildingBoardName
                        })
                    })
                    let arr = this.state.allDeviceList.concat(updateList);
                    this.setState({
                        buildList: updateList,
                        allDeviceList: arr,
                    })

                }
            })
        getData("api/commons/device/radio/broadcasts", {
            userId,
            token: sessionStorage.getItem("token")
        })
            .then((res) => {
                return res.json()
            })
            .then((result) => {
                if (result.code == 200 && Array.isArray(result.data)) {
                    let arr = this.state.allDeviceList.concat(result.data);
                    // let updateBroadcastList = [];
                    //需要剔除一下没有设备的广播楼宇
                    // result.data.forEach((item)=>{
                    //     if(Array.isArray(item.devices) && item.devices.length > 0){
                    //         updateBroadcastList.push(item);
                    //     }
                    // })
                    this.setState({
                        boardList: result.data,
                        allDeviceList: arr,
                    })
                }
            })

        if (type === 1) {
            this.setState({
                chooseDeviceList: JSON.parse(JSON.stringify(this.state.selectDeviceList))
            })
        }
        this.setState({
            isShowSelectObj: true,
        })
    }
    cancelObjModal = () => {
        this.setState({
            isShowSelectObj: false,
        })
    }
    showBuildList = () => {
        this.setState({
            isShowBuildList: !this.state.isShowBuildList
        })
    }
    showClassList = () => {
        this.setState({
            isShowClassList: !this.state.isShowClassList
        })
    }
    showBoardList = () => {
        this.setState({
            isShowBoardList: !this.state.isShowBoardList
        })
    }
    //选择设备
    chooseDevice = (obj, type) => {
        let {
            chooseDeviceList
        } = this.state;
        let newList = [];
        let sign = 0;  // 0是添加， 1是删除
        if (type) {
            if (obj.boardId) { //班牌
                chooseDeviceList.forEach((item) => {
                    if (item.boardId === obj.boardId) { //已存在
                        sign = 1;
                    }
                })
                if (sign === 0) {
                    chooseDeviceList.push(obj);
                    newList = chooseDeviceList;
                } else {
                    message.warn('不能重复选择', 3)
                    return;
                }

            } else if (obj.buildingBoardId) { //楼牌
                chooseDeviceList.forEach((item) => {
                    if (item.buildingBoardId === obj.buildingBoardId) { //已存在
                        sign = 1;
                    }
                })
                if (sign === 0) {
                    chooseDeviceList.push(obj);
                    newList = chooseDeviceList;
                } else {
                    message.warn('不能重复选择', 3)
                    $(this.refs.search_device).val("");
                    $(this.refs.search_device).focus();
                    return;
                }
            } else if (obj.buildingId) { //广播
                chooseDeviceList.forEach((item) => {
                    if (!item.buildingBoardId && item.buildingId === obj.buildingId) { //已存在
                        sign = 1;
                    }
                })
                if (sign === 0) {
                    chooseDeviceList.push(obj);
                    newList = chooseDeviceList;
                } else {
                    message.warn('不能重复选择', 3)
                    return;
                }
            } else {
                return;
            }
        } else {
            if (obj.boardId) { //班牌
                chooseDeviceList.forEach((item) => {
                    if (item.boardId === obj.boardId) { //已存在
                        sign = 1;
                    }
                })
                if (sign === 0) {
                    chooseDeviceList.push(obj);
                    newList = chooseDeviceList;
                } else {
                    chooseDeviceList.forEach((item) => {
                        if (item.boardId !== obj.boardId) {
                            newList.push(item);
                        }
                    })
                }

            } else if (obj.buildingBoardId) { //楼牌
                chooseDeviceList.forEach((item) => {
                    if (item.buildingBoardId === obj.buildingBoardId) { //已存在
                        sign = 1;
                    }
                })
                if (sign === 0) {
                    chooseDeviceList.push(obj);
                    newList = chooseDeviceList;
                } else {
                    chooseDeviceList.forEach((item) => {
                        if (item.buildingBoardId !== obj.buildingBoardId) {
                            newList.push(item);
                        }
                    })
                }
            } else if (obj.buildingId) { //广播
                chooseDeviceList.forEach((item) => {
                    if (!item.buildingBoardId && item.buildingId === obj.buildingId) { //已存在
                        sign = 1;
                    }
                })
                if (sign === 0) {
                    chooseDeviceList.push(obj);
                    newList = chooseDeviceList;
                } else {
                    chooseDeviceList.forEach((item) => {
                        if (!item.buildingBoardId && item.buildingId !== obj.buildingId) {
                            newList.push(item);
                        }
                    })
                }
            } else {
                return;
            }
        }
        // console.log(newList)
        this.setState({
            chooseDeviceList: newList
        })

    }
    //搜索设备
    searchDevice = (e) => {
        let {
            allDeviceList
        } = this.state;
        var text = $(e.target).val();
        console.log(text, allDeviceList);
        var that = this;
        //yun/user/{size}/{page}/{name}
        var arr = [];
        that.setState({
            forceHidden: false
        })
        if (!text) {
            this.setState({
                searchDeviceList: arr
            })
            return;
        }
        if (allDeviceList.length === 0) {
            return;
        }
        allDeviceList.forEach((item) => {
            if (
                (item.boardName && item.boardName.indexOf(text) !== -1) ||
                (item.BuildingName && item.BuildingName.indexOf(text) !== -1) ||
                (item.buildingBoardName && item.buildingBoardName.indexOf(text) !== -1)) {
                arr.push(item);
            }
        })
        that.setState({
            searchDeviceList: arr,
            forceHidden: false
        })
    }
    allChecked = (key, e) => {
        //全选功能
        let {
            chooseDeviceList,
            buildList,
            classList,
            boardList
        } = this.state;
        let isAdd = $(e.target).attr('class').indexOf('active') === -1 ? true : false;
        let newList = [];
        if (isAdd) {
            //全添加操作
            if (key === 'build') {
                buildList.forEach((item) => {
                    let isExist = false;
                    chooseDeviceList.forEach((item2) => {
                        if (item.buildingBoardId === item2.buildingBoardId) {
                            isExist = true;
                        }
                    })
                    if (!isExist) {
                        chooseDeviceList.push(item);
                    }
                })
            } else if (key === 'class') {
                classList.forEach((item) => {
                    let isExist = false;
                    chooseDeviceList.forEach((item2) => {
                        if (item.boardId === item2.boardId) {
                            isExist = true;
                        }
                    })
                    if (!isExist) {
                        chooseDeviceList.push(item);
                    }
                })
            } else if (key === 'board') {
                //额外处理一下广播终端各个子列表的显示，需要判断子列表是否包含设备
                let updateBoardList = [];
                boardList.forEach((item) => {
                    if (item.devices.length > 0) {
                        updateBoardList.push(item);
                    }
                })
                updateBoardList.forEach((item) => {
                    let isExist = false;
                    chooseDeviceList.forEach((item2) => {
                        if (!item2.buildingBoardId && item.buildingId === item2.buildingId) {
                            isExist = true;
                        }
                    })
                    if (!isExist) {
                        chooseDeviceList.push(item);
                    }
                })
            }
        } else {
            //全删除操作
            if (key === 'build') {
                buildList.forEach((item) => {
                    let ind;
                    chooseDeviceList.forEach((item2, index) => {
                        if (item.buildingBoardId === item2.buildingBoardId) {
                            ind = index;
                        }
                    })
                    if (typeof ind === 'number') {
                        chooseDeviceList.splice(ind, 1);
                    }
                })
            } else if (key === 'class') {
                classList.forEach((item) => {
                    let ind;
                    chooseDeviceList.forEach((item2, index) => {
                        if (item.boardId === item2.boardId) {
                            ind = index;
                        }
                    })
                    if (typeof ind === 'number') {
                        chooseDeviceList.splice(ind, 1);
                    }
                })
            } else if (key === 'board') {
                //额外处理一下广播终端各个子列表的显示，需要判断子列表是否包含设备
                let updateBoardList = [];
                boardList.forEach((item) => {
                    if (item.devices.length > 0) {
                        updateBoardList.push(item);
                    }
                })
                updateBoardList.forEach((item) => {
                    let ind;
                    chooseDeviceList.forEach((item2, index) => {
                        if (!item2.buildingBoardId && item.buildingId === item2.buildingId) {
                            ind = index;
                        }
                    })
                    if (typeof ind === 'number') {
                        chooseDeviceList.splice(ind, 1);
                    }
                })
            }
        }
        this.setState({
            chooseDeviceList: chooseDeviceList
        })
    }
    deleteDevice = (index) => {
        let {
            chooseDeviceList
        } = this.state;
        chooseDeviceList.splice(index, 1);
        this.setState({
            chooseDeviceList: chooseDeviceList
        })
    }
    deviceSelected = () => {
        //确定已选设备
        let {
            chooseDeviceList,
            allDeviceList,
            buildList,
            boardList,
            classList
        } = this.state;
        let buildArr = [], boardArr = [], classArr = [], selectedObjList = [];
        chooseDeviceList.forEach((item) => {
            if (item.boardId) { //班牌
                classArr.push(item);
            } else if (item.buildingBoardId) { //楼牌
                buildArr.push(item);
            } else if (item.buildingId) { //广播
                boardArr.push(item);
            }
        })
        //处理楼牌
        if (buildArr.length > 0 && buildArr.length < buildList.length) {
            let deviceNameList = buildArr.map((item) => {
                return item.buildingBoardName;
            })
            let deviceIdList = buildArr.map((item) => {
                return item.buildingBoardId;
            })
            let obj = {
                name: '部分楼牌',
                key: 'build',
                deviceNameList: deviceNameList,
                deviceIdList: deviceIdList
            }
            selectedObjList.push(obj);
        } else if (buildArr.length > 0 && buildArr.length === buildList.length) {
            let deviceNameList = buildArr.map((item) => {
                return item.buildingBoardName;
            })
            let deviceIdList = buildArr.map((item) => {
                return item.buildingBoardId;
            })
            let obj = {
                name: '全部楼牌',
                key: 'build',
                deviceIdList: deviceIdList,
                deviceNameList: deviceNameList
            }
            selectedObjList.push(obj);
        }
        //处理班牌
        if (classArr.length > 0 && classArr.length < classList.length) {
            let deviceNameList = classArr.map((item) => {
                return item.boardName;
            })
            let deviceIdList = classArr.map((item) => {
                return item.boardId;
            })
            let obj = {
                name: '部分班牌',
                key: 'class',
                deviceNameList: deviceNameList,
                deviceIdList: deviceIdList
            }
            selectedObjList.push(obj);
        } else if (classArr.length > 0 && classArr.length === classList.length) {
            let deviceNameList = classArr.map((item) => {
                return item.boardName;
            })
            let deviceIdList = classArr.map((item) => {
                return item.boardId;
            })
            let obj = {
                name: '全部班牌',
                key: 'class',
                deviceIdList: deviceIdList,
                deviceNameList: deviceNameList
            }
            selectedObjList.push(obj);
        }
        //处理广播
        if (boardArr.length > 0 && boardArr.length < boardList.length) {
            let deviceNameList = boardArr.map((item) => {
                return item.buildingName;
            })
            let deviceIdList = boardArr.map((item) => {
                return item.buildingId;
            })
            let deviceList = boardArr.map(item => {
                return item.devices
            })
            let obj = {
                name: '部分广播终端',
                key: 'board',
                deviceNameList: deviceNameList,
                deviceIdList: deviceIdList,
                Devices: deviceList
            }
            selectedObjList.push(obj);
        } else if (boardArr.length > 0 && boardArr.length === boardList.length) {
            let deviceNameList = boardArr.map((item) => {
                return item.buildingName;
            })
            let deviceIdList = boardArr.map((item) => {
                return item.buildingId;
            })
            let deviceList = boardArr.map(item => {
                return item.devices
            })
            let obj = {
                name: '全部广播终端',
                key: 'board',
                deviceIdList: deviceIdList,
                deviceNameList: deviceNameList,
                Devices: deviceList
            }
            selectedObjList.push(obj);
        }
        this.setState({
            selectDeviceList: JSON.parse(JSON.stringify(chooseDeviceList)),
            selectedObjList,
            isShowSelectObj: false,
            isShowBuildList: false,
            isShowClassList: false,
            isShowBoardList: false
        }, () => this.props.setDevices(JSON.parse(JSON.stringify(chooseDeviceList))))
    }
    deleteSelectedDevice = (index) => {
        //删除弹出框外已选设备
        let {
            selectDeviceList
        } = this.state;
        selectDeviceList.splice(index, 1);
        this.setState({
            selectDeviceList
        })
    }

    // 预览附件
    preViewFile(item) {
        let filePath = item.url;
        filePath = filePath.replace(/[\\]+/g, '/');
        let base64 = new Base64();
        let url = encodeURIComponent(base64.encode(filePath));
        let previewIP = JSON.parse(sessionStorage.getItem("previewIP"));
        let webSvrAddr = previewIP[0].webSvrAddr;
        let edu = JSON.parse(sessionStorage.getItem('userInfo'))
        window.open(`${webSvrAddr}onlinePreview?url=${url}&eduId=${edu.eduId}`);
    }
    //删除附件
    deleteFile = (index) => {
        let {
            attachments
        } = this.state
        let fileArr = attachments.concat([]);
        fileArr.splice(index, 1);
        this.props.setAttachmentsList(fileArr);
        this.setState({
            attachments: fileArr
        })
    }

    checkItem = (typeId, obj) => {
        this.props.setReleaseTypeId(typeId);
        console.log(this.props.typeList)
        console.log(typeId)
        console.log(obj)
        let group = []
        let group1 = [];
        if (obj.scopeIdentityList.length > 0) {
            obj.scopeIdentityList.forEach(i => {
                group.push({
                    label: i.identityName, value: i.identityCode, checked: false
                })
            })
            group.forEach(item => {
                item.checked = false;
                obj.scope.forEach(itm => {
                    if (item.value == itm) {
                        item.checked = true;
                        group1.push(item)
                    }
                })
            })
        }
        // let group = this.state.group, group1 = [];
        // if (obj.scopeIdentityList.length > 0) {
        //     group.forEach(item => {
        //         item.checked = false;
        //         obj.scope.forEach(itm => {
        //             if (item.value == itm) {
        //                 item.checked = true;
        //                 group1.push(item);
        //             }
        //         })
        //     })
        // } else {
        //     group.forEach(item => {
        //         item.checked = false;
        //     })
        // }
        console.log(group)
        console.log(group1)
        this.setState({
            group,
            group1
        }, () => {
            this.props.setReleaseScope(group);
        })
    }


    selectUserChange = (value) => {  //控制选择对象弹窗显隐
        this.setState({
            selectUserVisible: value
        })
    };

    getSelectList = (obj) => {   //获取选择对象选择的用户列表（新）
        let receiver = {}
        receiver.persons = obj.selectUserList;
        this.setState({
            selectUserList: obj.selectUserList
        }, () => {
            this.props.setReceiver(receiver)
        })
    };

    //部门选择
    SelectOptionB = (item) => {
        console.log("选择的item:", item);
        let newList = [];
        newList.push(item);
        this.setState({
            cascaderValue: item.text
        }, () => {
            this.props.setReleaseDepartment(newList)
        })
    }
    onSearch = (value) => {
        console.log("搜索值:", value);
    }

    //2023-07-03当没有搜出部门，跳转到部门设置
    goDepSetting = (e) => {
        window.open(`${sessionStorage.getItem('baseUrl')}/index.html?lg_tk=${getQueryVariable('lg_tk')}&lg_ic=${getQueryVariable('lg_ic')}#/organization`)
    }

    render() {

        let {
            datalistA,
            selectValue,
            group,
            radioValue,
            toped,
            synced,
            releaseDepList,
            selectDepList,
            selectUserVisible,
            selectUserList,
            totalNum,
            isShowSelectObj,
            isShowBuildList,
            isShowClassList,
            isShowBoardList,
            chooseDeviceList,
            buildList,
            boardList,
            classList,
            selectDeviceList,
            isShowSelectDep,
            loading,
            attachments,
            searchDeviceList,
            forceHidden,
            over,
            noticeTitle,
            officePlatform,
            cascaderValue,
            group1,
            userInfo,
            isAdvancedAdmin,
            innerTypeId,
            date,
        } = this.state
        console.log('group1', group1);

        let $this = this;
        let fileArr = attachments.concat([]);
        const uploadProps = {
            action: this.state.schoolInfo.itemUrl + 'api/commons/file/batch/upload?modelName=noticeCenter',
            multiple: true,
            name: 'files',
            headers: {
                Authorization: getQueryVariable('lg_tk') || sessionStorage.getItem('token'),
            },
            onStart(file) {
                $this.setState({
                    loading: true
                })
                console.log('onStart', file, file.name);
            },
            onSuccess(ret) {
                fileArr.push(ret.data[0]);
                $this.setState({
                    loading: false,
                    attachments: fileArr
                })
                $this.props.setAttachmentsList(fileArr);

                console.log(fileArr, 'onSuccess', ret);
            },
            onError(err) {
                $this.setState({
                    loading: false
                })
                console.log('onError', err);
            },
            beforeUpload(file, fileList) {
                console.log(file, 'fileList', fileList);
                return new Promise(resolve => {
                    if (typeArr.includes(GetExtensionFileName(file.name)) && fileList.length < 6 && fileArr.length < 5) {
                        console.log('start check', fileArr);
                        setTimeout(() => {
                            console.log('check finshed');
                            resolve(file);
                        }, 1000);
                    } else {
                        if ((fileList.length + fileArr.length) > 5) {
                            message.warn(`只能上传五个文件！`);
                        } else {
                            message.warn(`不支持当前.${GetExtensionFileName(file.name)}文件类型！`);
                        }
                        return;
                    }
                });

            },
        };

        let buildArr = [], boardArr = [], classArr = [], buildSign, boardSign, classSign, userSign, userArr = [];
        chooseDeviceList.forEach((item) => {
            if (item.boardId) { //班牌
                classArr.push(item);
            } else if (item.buildingBoardId) { //楼牌
                buildArr.push(item);
            } else if (item.buildingId) { //广播
                boardArr.push(item);
            }
        })


        //处理楼牌
        if (buildArr.length > 0 && buildArr.length < buildList.length) {
            buildSign = "contain";
        } else if (buildArr.length > 0 && buildArr.length === buildList.length) {
            buildSign = "active";
        }
        //处理班牌
        if (classArr.length > 0 && classArr.length < classList.length) {
            classSign = "contain";
        } else if (classArr.length > 0 && classArr.length === classList.length) {
            classSign = "active";
        }
        //处理广播
        if (boardArr.length > 0 && boardArr.length < boardList.length) {
            boardSign = "contain";
        } else if (boardArr.length > 0 && boardArr.length === boardList.length) {
            boardSign = "active";
        }
        return (
            <div className='create-notice'>
                {
                    !over ?
                        <>
                            <div className='create-notice-top'>
                                <div className='title'>
                                    <span className='notice-span'>
                                        <span className='is-must'>*</span>
                                        标题:
                                    </span>
                                    <LgInput maxLength={30} className="" value={noticeTitle} onChange={(e) => { this.props.setNoticeTitle(e.currentTarget.value); this.setState({ noticeTitle: e.currentTarget.value }) }} placeholder='请输入公告标题' style={{ width: '755px' }}></LgInput>
                                </div>
                                <div className='type-select'>
                                    <div>
                                        <span className='notice-span'>
                                            <span className='notice-span-icon' title='只有公告类型负责人才可以发布该类型公告。'></span>
                                            类型:
                                        </span>
                                    </div>
                                    <div >
                                        <LgRadio.Group value={radioValue} onChange={(nextValue, itm) => this.setState({
                                            radioValue: nextValue,
                                            innerTypeId: this.props?.typeList[nextValue]?.innerTypeId || null,
                                        }, () => console.log(nextValue, 'itm111', itm, 'this.props1', this.props?.typeList)
                                        )}>
                                            {
                                                this.props.typeList && this.props.typeList.map((item, index) => {
                                                    return (
                                                        <LgRadio className="g006-form-1-item" value={index} onChange={() => this.checkItem((item.typeId || item.innerTypeId), item)} >{item.typeName}</LgRadio>
                                                    )
                                                })
                                            }
                                        </LgRadio.Group>
                                    </div>
                                </div>
                                <div className='can-view-people'>
                                    <span className='notice-span'>
                                        可查看对象:
                                    </span>
                                    <div className='check-box'>
                                        {
                                            // group.map((item, index) => (
                                            group1.map((item, index) => (
                                                <LgCheckbox className={index === 4 || item.label == '其他' ? "g006-form-1-item g006-form-1-item-other" : "g006-form-1-item"} key={"checkbox" + index} checked={item.checked} onChange={this.onChange} value={index} label={item.label} />
                                                // <LgCheckbox disabled className={index === 4 ? "g006-form-1-item g006-form-1-item-other" : "g006-form-1-item"} key={"checkbox" + index} checked={item.checked} onChange={this.onChange} value={index} label={item.label} />
                                            ))
                                        }
                                        {
                                            group1.length > 0 && group1[group1.length - 1]?.label == '其他' ?
                                                <span className='notice-span-icon' title='包含其他教职工和临时用户等用户。'></span>
                                                : ''
                                        }
                                        {
                                            group1.length > 0 ?
                                                ''
                                                : <span >没有设置可查看对象</span>
                                        }
                                    </div>
                                </div>
                                <div className='publish-departments'>
                                    <div>
                                        <span className='notice-span'>
                                            <span className='is-must'>*</span>
                                            发布部门:
                                        </span>
                                    </div>
                                    <div className="publish-departments-right">
                                        <LgSelect placeholder={"请选择部门..."}
                                            datalist={this.props.departmentList}
                                            SelectOption={this.SelectOptionB}
                                            value={cascaderValue}
                                            openSearch={true}
                                            onSearch={this.onSearch}
                                            className='select-dep'
                                            customEmpty={<div className='select-dep-empty'><LgEmpty>暂无数据
                                                {
                                                    userInfo.userType == '0' || isAdvancedAdmin == 1 ?
                                                        <span className='go-set-dep' onClick={this.goDepSetting}>去设置</span>
                                                        : ''
                                                }
                                            </LgEmpty></div>}
                                        // ban={true}
                                        ></LgSelect>
                                    </div>
                                </div>
                                <div className='notice-content'>
                                    <span className='notice-span'>
                                        <span className='is-must'>*</span>
                                        内容:
                                    </span>
                                    <MyEditor id='editor' getHtmlContent={(html) => { this.props.setNoticeContent(html && html !== '<p><br></p>' ? html : '') }} value={this.state.noticeContent} clear={this.state.clear} />
                                </div>
                                <div className='file-upload'>
                                    <span className='notice-span'>
                                        附件:
                                    </span>
                                    <LgUpload {...uploadProps}>
                                        <LgButton backgroundType='translucent' border type='info'>上传文件</LgButton>
                                    </LgUpload>
                                    <span className='upload-tips'>(支持上传.doc/.docx/.pdf/.ppt/.jpg/.jpeg/.png/.xls/.zip格式的文件)</span>
                                    {
                                        loading ?
                                            <LgLoadingDotRotation size="small" className='upload-circle' text={'正在上传~'} />
                                            : ''
                                    }
                                    {
                                        attachments.length > 0 ?
                                            <div className='file-list'>
                                                {
                                                    attachments.map((item, index) => {
                                                        return (
                                                            <div className='file-item'>
                                                                <div className='file-info'>
                                                                    <i className={`file-icon file-icon-${GetExtensionFileName(item.fileName)}`}></i>
                                                                    <span className='file-name'>{item.fileName}</span>
                                                                    <span className='file-size'>{item.size > 1048576 ? (item.size / 1024 / 1024).toFixed(1) + 'MB'
                                                                        : (item.size / 1024).toFixed(1) + 'KB'}</span>
                                                                </div>
                                                                <div>
                                                                    <LgButton onClick={() => this.preViewFile(item)} split shapeType='text' type='info'>预览</LgButton>
                                                                    <LgButton onClick={() => this.deleteFile(index)} split shapeType='text' type='fail'>删除</LgButton>
                                                                </div>
                                                            </div>
                                                        )
                                                    })
                                                }
                                            </div> : ''
                                    }

                                </div>
                                {
                                    innerTypeId == 3 ?
                                    <div className='publish-finish-time'>
                                        <div>
                                            <span className='notice-span'>
                                                <span className='is-must'>*</span>
                                                显示截止时间:
                                            </span>
                                        </div>
                                        <div className="publish--finish-right">
                                            <LgDatePicker value={date} disabledDate={time => time.getTime() < Date.now() - 8.64e7} placeholder="请选择日期" onChange={e => { this.setState({ date: e }); this.props.setDisplayEndTime(e); }} />
                                        </div>
                                    </div>
                                    : ''
                                }
                            </div>
                            <div className='create-notice-bottom' >
                                <div className='advanced-settings' onClick={() => { this.props.setAdvanced() }}>
                                    <span>高级设置</span>
                                    <i className={'advanced-settings-icon ' + (this.props.isAdvanced ? 'advanced-settings-icon-up' : 'advanced-settings-icon-down')}></i>
                                </div>
                                <div className='advanced-settings-bottom'>
                                    <div className='top-sync'>
                                        <span className='notice-span'>
                                            是否置顶:
                                        </span>
                                        <LgSwitch checked={toped} onClick={() => { this.setState({ toped: !toped }, () => this.props.setIsTop(this.state.toped === true ? '1' : '0')); }}></LgSwitch>
                                        {/* <span className='sync-official'>是否同步到官网:</span>
                                        <LgSwitch checked={synced} onClick={() => { this.setState({ synced: !synced }, () => this.props.setIsSynced(this.state.synced === true ? '1' : '0')); }}></LgSwitch> */}
                                        {/* <span className='sync-module'>选择需同步官网模块:</span>
                                        <LgSelect className='select-module' datalist={datalistA}
                                            SelectOption={this.SelectOptionA}
                                            value={selectValue}>
                                        </LgSelect>
                                        <LgSelect className='select-module' datalist={datalistA}
                                            SelectOption={this.SelectOptionA}
                                            value={selectValue}>
                                        </LgSelect> */}
                                    </div>
                                    <div className='remind-person'>
                                        <div className='remind-top'>
                                            <div>
                                                <span className='notice-span'>
                                                    <span className='notice-span-icon' title='已选择的提醒对象会收到发布公告的消息提醒。'></span>
                                                    提醒对象:
                                                </span>
                                            </div>
                                            <div className='remind-top-right'>
                                                <div>
                                                    {
                                                        selectUserList.length > 0 ? selectUserList.slice(0, 10).map((item, index) => {
                                                            return (
                                                                <div className='selected-one' key={index}>{item.name || item.userName}
                                                                    {
                                                                        item.userId ?
                                                                            <span style={{
                                                                                color: "#999"
                                                                            }}>({item.userId})</span> :
                                                                            item.groupType ?
                                                                                <>
                                                                                    <span style={{
                                                                                        color: "#999"
                                                                                    }}>({groupTypeInfo[item.groupType]})</span>
                                                                                    {
                                                                                        item?.totalCount ?
                                                                                            <span style={{
                                                                                                color: "#999"
                                                                                            }}>({item.totalCount}人)</span>
                                                                                            : ''
                                                                                    }
                                                                                </>
                                                                                :
                                                                                ""
                                                                    }
                                                                    <i className="delete-logo" onClick={() => this.deleteSelectedUser(index)}></i>
                                                                </div>
                                                            )
                                                        }) : ''
                                                    }
                                                    {
                                                        selectUserList.length > 10 ?
                                                            <span style={{ float: "left", margin: "0 5px", fontSize: "20px", lineHeight: "20px" }}>...</span> :
                                                            ""
                                                    }
                                                </div>
                                                <div className='remind-bottom' style={{ marginTop: selectUserList.length > 0 ? '' : '18px' }}>
                                                    {
                                                        selectUserList.length > 0 ?
                                                            <><span className='notice-span'>
                                                                已选<span className='remind-num'>{selectUserList.length}</span>人
                                                            </span><LgButton className='remind-empty' size='mini' onClick={() => this.clear(1)} backgroundType='translucent' border type='fail'>清空</LgButton></>
                                                            : ''
                                                    }
                                                    <LgButton className='remind-open-select' onClick={() => {
                                                        this.setState({ selectUserVisible: true });
                                                    }} size='mini' backgroundType='translucent' border type='info'>选择</LgButton>
                                                    {
                                                        selectUserVisible ?
                                                            <SelectUserModal
                                                                // width='950px'
                                                                className='select-user-item lg-skin-s2'
                                                                title={'选择提醒对象'}
                                                                // groupUserType={['0','1']}
                                                                type={'edu'}
                                                                schoolId={this.state.userInfo.eduId}
                                                                baseUrl={officePlatform[0].webSvrAddr ? officePlatform[0].webSvrAddr : ''} //http://192.168.122.124:22101/office-platform/
                                                                token={sessionStorage.getItem('token') || getQueryVariable('lg_tk')}
                                                                visible={selectUserVisible}
                                                                getSelectResult={this.getSelectList}
                                                                selectList={selectUserList}
                                                                changeVisible={this.selectUserChange} />
                                                            : ''
                                                    }
                                                    {/* {
                                                        selectUserVisible ?
                                                            <CollectSelectModal
                                                                title="选择用户"
                                                                visible={selectUserVisible}  //控制显隐
                                                                originList={selectUserList}  //已选择的用户列表
                                                                getList={this.getSelectList1}  //接收选择的对象
                                                                changeVisible={this.selectUserChange}  //控制显隐的函数
                                                                setNum={(num) => this.setState({ totalNum: num })}
                                                            />
                                                            : ''
                                                    } */}
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                </div>

                            </div></>
                        : <Spin size="large" />
                }

            </div>
        )
    }
}

export default CreateNotice;